package br.com.portalecbahia;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import br.com.portalecbahia.connectionservices.SynchronizeActions;
import br.com.portalecbahia.connectionservices.SynchronizeLoginTwitter;
import br.com.portalecbahia.connectionservices.SynchronizeTwitter;
import br.com.portalecbahia.customize.ActionListAdapter;
import br.com.portalecbahia.customize.PullToRefreshListView;
import br.com.portalecbahia.customize.PullToRefreshListView.OnRefreshListener;
import br.com.portalecbahia.customize.ShareListAdapter;
import br.com.portalecbahia.dao.ActionDAO;
import br.com.portalecbahia.dao.MatchDAO;
import br.com.portalecbahia.listner.ActionListeners;
import br.com.portalecbahia.listner.TwitterListeners;
import br.com.portalecbahia.model.Action;
import br.com.portalecbahia.model.Match;
import br.com.portalecbahia.model.Share;
import br.com.portalecbahia.model.Stadium;
import br.com.portalecbahia.util.PortalECBahiaUtil;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.google.analytics.tracking.android.EasyTracker;
import com.raptureinvenice.webimageview.image.WebImageView;

public class ActionActivity extends ListActivity implements ActionListeners,TwitterListeners, DialogListener{ 

	private ImageView updateIMG;
	private SynchronizeActions taskAction;
	private Context context;
	private List<Action> lActions;
	private ListAdapter adapterListAction;
	private Match match;
	private TextView dateLastUpdateTX;
	private TextView teamHomeTX;
	private TextView teamAwayTX;
	private ImageView scoreHomeIMG;
	private ImageView scoreAwayIMG;
	private TextView atualizadoTX;
	private WebImageView flagHomeTeamTMG ;
	private WebImageView flagAwayTeamTMG;

    private SharedPreferences mPrefs;		
	public static Twitter mTwitter;
	public TextView post;

	private Facebook facebook = new Facebook("386384074776856");

	private int sizeList = 0;
	
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
       
        super.setContentView(R.layout.actions);

        EasyTracker.getInstance().setContext(this);
        
        context = this;
        updateIMG 		 = (ImageView) findViewById(R.id.updateIMG);
        dateLastUpdateTX = (TextView)findViewById(R.id.dateLastUpdateTX);
        teamHomeTX 		 = (TextView)findViewById(R.id.teamHomeTX);
        teamAwayTX 		 = (TextView)findViewById(R.id.teamAwayTX);
        scoreHomeIMG 	 = (ImageView) findViewById(R.id.scoreHomeIMG);
        scoreAwayIMG 	 = (ImageView) findViewById(R.id.scoreAwayIMG);
        atualizadoTX	 = (TextView)findViewById(R.id.atualizadoTX);
		flagHomeTeamTMG  = (WebImageView) findViewById(R.id.flagHomeIMG);
		flagAwayTeamTMG  = (WebImageView) findViewById(R.id.flagAwayIMG);
        
        Bundle loadInfo = getIntent().getExtras();
        match = (Match) loadInfo.getSerializable("match");
        
        ((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
            	if(PortalECBahiaUtil.haveNetworkConnection(context)){
            		taskAction = new SynchronizeActions(context);
            		taskAction.execute(match);
            	}else{
        			Toast.makeText(context, getString(R.string.internetOff), Toast.LENGTH_LONG).show();
        			  ((PullToRefreshListView) getListView()).onRefreshComplete();
            	}
            }
        });
        fillMatchInformation();
        
        	listAllAction();
       
        	
        updateList(new View(context));
        
        
        

    }
    @Override
    public void onStart() {
      super.onStart();
      EasyTracker.getInstance().activityStart(this); // Add this method.
    }

    @Override
    public void onStop() {
      super.onStop();
      EasyTracker.getInstance().activityStop(this); // Add this method.
    }
    public void stadiumDetail(View view){
    	Intent intent = null;
		Stadium stadium = new Stadium();
		stadium.setId(match.getStadiumId());
		stadium.setName(match.getStadimName());

		intent = new Intent(this, StadiumActivity.class);
		intent.putExtra("stadium", stadium);

		startActivity(intent);
		return;

    }
   
	private void fillMatchInformation() {
		
		teamHomeTX.setText(match.getHomeTeamShortName());
		teamAwayTX.setText(match.getAwayTeamShortName());
		
	        if(match.getHomeTeamUrlImage() !=null){
	        	WebImageView.setDiskCachingDefaultCacheTimeout(60 * 60* 24*30); // 1 month expiration
	        	flagHomeTeamTMG.setImageWithURL(context,  match.getHomeTeamUrlImage());        	 
	        }
	        
	        if(match.getAwayTeamUrlImage() !=null){
	        	WebImageView.setDiskCachingDefaultCacheTimeout(60 * 60* 24*30); // 1 month expiration
	        	flagAwayTeamTMG.setImageWithURL(context,  match.getAwayTeamUrlImage());        	 
	        }
	        
	        SimpleDateFormat formatUTC = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	        formatUTC.setTimeZone(TimeZone.getTimeZone("UTC"));
	        Date now=null;
			try {
				now = (Date) (new SimpleDateFormat("yyyy-MM-dd HH:mm")).parse(formatUTC.format(new Date()));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	       
		
        
       
        if(match.getHomeGoal()!=null && !now.before(match.getDateUTC()) ){
        	if(match.getHomeGoal()==0){
        		scoreHomeIMG.setImageResource(R.drawable.zero);
        	}
        	else if(match.getHomeGoal()==1){
        		scoreHomeIMG.setImageResource(R.drawable.one);
        	}
        	else if(match.getHomeGoal()==2){
        		scoreHomeIMG.setImageResource(R.drawable.two);
		    }
        	else if(match.getHomeGoal()==3){
        		scoreHomeIMG.setImageResource(R.drawable.three);
        	}
        	else if(match.getHomeGoal()==4){
        		scoreHomeIMG.setImageResource(R.drawable.four);
        	}
        	else if(match.getHomeGoal()==5){
        		scoreHomeIMG.setImageResource(R.drawable.five);
        	}
        	else if(match.getHomeGoal()==6){
        		scoreHomeIMG.setImageResource(R.drawable.six);
        	}
        	else if(match.getHomeGoal()==7){
        		scoreHomeIMG.setImageResource(R.drawable.seven);
        	}
        	else if(match.getHomeGoal()==8){
        		scoreHomeIMG.setImageResource(R.drawable.eight);
        	}
        	else if(match.getHomeGoal()==9){
        		scoreHomeIMG.setImageResource(R.drawable.nine);
        	}else{
        		scoreHomeIMG.setVisibility(View.INVISIBLE);	
        	}
        }else{
        	
        	scoreHomeIMG.setVisibility(View.INVISIBLE);
        }
	        
	        
        if(match.getAwayGoal()!=null && !now.before(match.getDateUTC()) ){
        	if(match.getAwayGoal()==0){
        		scoreAwayIMG.setImageResource(R.drawable.zero);
        	}
        	else if(match.getAwayGoal()==1){
        		scoreAwayIMG.setImageResource(R.drawable.one);
        	}
        	else if(match.getAwayGoal()==2){
        		scoreAwayIMG.setImageResource(R.drawable.two);
        	}
        	else if(match.getAwayGoal()==3){
        		scoreAwayIMG.setImageResource(R.drawable.three);
        	}
        	else if(match.getAwayGoal()==4){
        		scoreAwayIMG.setImageResource(R.drawable.four);
        	}
        	else if(match.getAwayGoal()==5){
        		scoreAwayIMG.setImageResource(R.drawable.five);
        	}
        	else if(match.getAwayGoal()==6){
        		scoreAwayIMG.setImageResource(R.drawable.six);
        	}
        	else if(match.getAwayGoal()==7){
        		scoreAwayIMG.setImageResource(R.drawable.seven);
        	}
        	else if(match.getAwayGoal()==8){
        		scoreAwayIMG.setImageResource(R.drawable.eight);
        	}
        	else if(match.getAwayGoal()==9){
        		scoreAwayIMG.setImageResource(R.drawable.nine);
        	}else{
        		scoreAwayIMG.setVisibility(View.INVISIBLE);	
        	}
        }else{
        	scoreAwayIMG.setVisibility(View.INVISIBLE);
	    }
		
	}

	public void listAllAction(View view) {

		listAllAction();
	}
	private void listAllAction() {
		
		lActions= new ArrayList<Action>();
		lActions.clear();
	    	
		lActions = new ActionDAO(this).findByMatch(match);   
		sizeList = lActions.size();
		if(lActions.size()<10){    		
			for (int i = 0; i < PortalECBahiaUtil.minimumListSize-sizeList; i++) {
				lActions.add(new Action());
			}
		}
		adapterListAction = (ListAdapter) new ActionListAdapter(this, lActions);
		
		setListAdapter(adapterListAction);
		String date = new ActionDAO(this).findLastUpdate
				(match);
		if("".equals(date)){
			atualizadoTX.setVisibility(View.INVISIBLE);
		}else{
			atualizadoTX.setVisibility(View.VISIBLE);
			dateLastUpdateTX.setText(date);
		}
	    	  
	}
	

	public void updateList(View view){
		if(PortalECBahiaUtil.haveNetworkConnection(context)){
			taskAction = new SynchronizeActions(context);
			taskAction.execute(match);
			animateUpdate();
    	}else{
			Toast.makeText(context, getString(R.string.internetOff), Toast.LENGTH_LONG).show();
			  ((PullToRefreshListView) getListView()).onRefreshComplete();
    	}

	}

	private void animateUpdate() {
		int   currentRotation = 0;
		RotateAnimation anim = new RotateAnimation(currentRotation, (360*4),
		Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,0.5f);
		currentRotation = (currentRotation + 45) % 360;
		anim.setInterpolator(new LinearInterpolator());
		anim.setDuration(4000);
		anim.setRepeatMode(Animation.INFINITE);
		anim.setRepeatCount(Animation.INFINITE);
		anim.setFillEnabled(true);
		anim.setFillAfter(true);
		updateIMG.startAnimation(anim);
		
	}

	@Override
	public void onSynchronizeActionComplete(Boolean response) {
		if(response){
			listAllAction();
			
			match =  new MatchDAO(this).findByPrimaryKey (match); 
	        fillMatchInformation();

		}else{
			Toast.makeText(context, getString(R.string.serverProblem), Toast.LENGTH_LONG).show();
		}
	    updateIMG.clearAnimation();
	    ((PullToRefreshListView) getListView()).onRefreshComplete();
		
	}
	
	public void positionList(){
		getListView().post(new Runnable(){
       	  public void run() {
       		  
       			  getListView().setSelection(sizeList);
       		 
       	  }
		});
	}
	String minutes;
	String description;
	public void openShare(View view){
		//SynchronizeLoginTwitter.disconnect();
		RelativeLayout rView  = ((RelativeLayout)view.getParent());
		minutes= ((TextView)rView.getChildAt(0)).getText()+"";
		description = ((TextView)rView.getChildAt(1)).getText()+"";

			ArrayList<Share> items = new ArrayList<Share>();
    		Share item = new Share();
    		item.setIconResource(R.drawable.icon_twitter);
    		item.setTitle("Twitter");
    		items.add(item);
    		item = new Share();
    		item.setIconResource(R.drawable.icon_facebook);
    		item.setTitle("Facebook");
    		items.add(item);
    		ShareListAdapter adapter = new ShareListAdapter(context, items);
    		AlertDialog.Builder builder = new Builder(context, R.style.AlertDialogCustom);
    		builder.setTitle("Compartilhe:");
    		builder.setAdapter(adapter, new DialogInterface.OnClickListener() {

    			@Override
    			public void onClick(DialogInterface dialog, int which) {
    				// TODO Auto-generated method stub
    				if(which ==0){
    					 // Create a new shared preference object to remember if the user has
    			        mPrefs = getSharedPreferences("twitterPrefs", MODE_PRIVATE);
    			        // Load the twitter4j helper
    			        mTwitter = new TwitterFactory().getInstance();
    			        // Tell twitter4j that we want to use it with our app
    			        mTwitter.setOAuthConsumer(PortalECBahiaUtil.CONSUMER_KEY, PortalECBahiaUtil.CONSUMER_SECRET);
    			    
    			        if (mPrefs.contains(PortalECBahiaUtil.PREF_ACCESS_TOKEN) && mPrefs.getString(PortalECBahiaUtil.PREF_ACCESS_TOKEN, null)!=null && mPrefs.getString(PortalECBahiaUtil.PREF_ACCESS_TOKEN_SECRET, null)!=null) {
    			            loginAuthorisedUser();
    			         }else{
//    			 	       	Intent intent = new Intent(this, TwitterConnector.class);//ServiceSelectActivity.class);
//    			 	       	startActivity(intent);
    			        	
    			     		new SynchronizeLoginTwitter(mTwitter, context).execute(PortalECBahiaUtil.CALLBACK_URL_ACTION);
    			         }

    				}else{
    					mPrefs = getPreferences(MODE_PRIVATE);
    			        String access_token = mPrefs.getString("access_token_face", null);
    			        long expires = mPrefs.getLong("access_expires", 0);
    			        if(access_token != null) {
    			            facebook.setAccessToken(access_token);
    			        }
    			        if(expires != 0) {
    			            facebook.setAccessExpires(expires);
    			        }
    			        
    			      
    			        if(!facebook.isSessionValid()) {

    			            authorize();
    			        }else{
    			        	 publishe();
    			        }
    				}
    			}

				
    			
    		});
    		builder.setNegativeButton("Sair", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			builder.create().show();
	}

  
  @SuppressWarnings("deprecation")
	private void authorize() {
		 facebook.authorize(this, new String[] {}, new DialogListener() {
         @Override
         public void onComplete(final Bundle values) {
             final SharedPreferences.Editor editor = mPrefs.edit();
             editor.putString("access_token_face", facebook.getAccessToken());
             editor.putLong("access_expires", facebook.getAccessExpires());
             editor.commit();
             publishe();
         }

         @Override
         public void onFacebookError(final FacebookError error) {
         	Log.i("Facebok","onFacebookError"+error.getMessage());
         	
         }

         @Override
         public void onError(final DialogError e) {
         	Log.i("Facebok","onError"+e.getMessage());
         }

         @Override
         public void onCancel() {
         	Log.i("Facebok","onCancel");
         }
     });
		
	}
  @Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

	    facebook.authorizeCallback(requestCode, resultCode, data);
	}
	private void publishe() {
		Bundle parameters = new Bundle(); 
	    
		parameters.putString("message", ""); 
	    parameters.putString("link", "");
	    parameters.putString("name", "PortalECBahia: "+minutes+" "+description); 
	    parameters.putString("picture", "http://mw2.google.com/mw-panoramio/photos/medium/31049149.jpg");
	    parameters.putString("description", " "); 
	    
      facebook.dialog(this, "stream.publish", parameters, this);// "stream.publish" is an API cal

			
	}

	 public  void loginAuthorisedUser() {
	    	// Create the twitter access token from the credentials we got previously
	        AccessToken at = new AccessToken(mPrefs.getString(PortalECBahiaUtil.PREF_ACCESS_TOKEN, null), mPrefs.getString(PortalECBahiaUtil.PREF_ACCESS_TOKEN_SECRET, null));
	        
	        mTwitter.setOAuthAccessToken(at); 

			AlertDialog.Builder builder = new Builder(this, R.style.AlertDialogCustom);
			LayoutInflater inflator = LayoutInflater.from(this);
			View view = inflator.inflate(R.layout.dialog_twitter, null);
			builder.setView(view);
			builder.setIcon(R.drawable.icon_twitter);
			builder.setTitle("Twitter");
			
	        post =(TextView) view.findViewById(R.id.post);
	        post.setText(minutes+" "+description+" "+"#PortalECBahia");
			builder.setPositiveButton("Enviar", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						
						 new SynchronizeTwitter(mTwitter,context).execute(post.getText().toString());
			           
					}
			});
	        builder.setNegativeButton("Sair", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});

	        
	        builder.show();

			
		}
	@Override
	public void onSynchronizeTwitComplete(Boolean response) {
		 if(response)
			 Toast.makeText(this, "Twit enviado com sucesso!", Toast.LENGTH_SHORT).show();
		 else		
			 Toast.makeText(this, "Twit nao enviado!", Toast.LENGTH_SHORT).show();
		
	}

	@Override
	public void onSynchronizeTwitterLoginComplete(Boolean response) {
		if(!response)		
   		 Toast.makeText(this, "Problemas com autenticacao no Twitter", Toast.LENGTH_SHORT).show();

	}
	
	 /**
     * Catch when Twitter redirects back to our {@link CALLBACK_URL}</br>
     * We use onNewIntent as in our manifest we have singleInstance="true" if we did not the
     * getOAuthAccessToken() call would fail
     */
     @Override
     protected void onNewIntent(Intent intent) {
    	 super.onNewIntent(intent);
         
    	 Uri uri = intent.getData();
         if (uri != null && uri.toString().startsWith(PortalECBahiaUtil.CALLBACK_URL_ACTION)) { // If the user has just logged in
        	 String oauthVerifier = uri.getQueryParameter("oauth_verifier");
 
        	 try {
        		 AccessToken at = mTwitter.getOAuthAccessToken(SynchronizeLoginTwitter.mReqToken, oauthVerifier);
        		 mTwitter.setOAuthAccessToken(at);
     
                 SynchronizeLoginTwitter.saveAccessToken(at);
                 
                 loginAuthorisedUser();                 

        	 } catch (TwitterException e) {
        		 Toast.makeText(this, "Problemas com autenticacao no Twitter", Toast.LENGTH_SHORT).show();
        	 }
         }
         
     }



     @Override
 	public void onComplete(Bundle values) {
 		if(values!=null && !"".equals(values.getString("post_id")) && values.getString("post_id")!=null){
 			Toast.makeText(this, "Post enviado com sucesso", Toast.LENGTH_LONG).show();
 		}
 		this.finish();
 		
 	}
 	@Override
 	public void onFacebookError(FacebookError error) {
        	Log.i("Facebok","onFacebookError"+error.getMessage());
 		
 	}
 	@Override
 	public void onError(DialogError error) {
        	Log.i("Facebok","DialogError"+error.getMessage());
 		
 	}
 	@Override
 	public void onCancel() {
        	Log.i("Facebok","onCancel");		
 	} 
     

 
}
